<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Arr;

class UniqueArrayValue implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    protected string $repeatName = '';
    public function __construct(protected string $key)
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // 提取所有指定 key 的值
        $values = array_column($value, $this->key);
        $arr = array_map(function ($value) {
            return is_string($value) || is_int($value) ? $value : 'N/A';
        }, $values);
        // 统计值的出现次数
        $counts = array_count_values($arr);
        //dd($counts);
        // 筛选出重复的值（出现次数 > 1）
        $duplicates = array_keys(array_filter($counts, function ($count) {
            return $count > 1;
        }));
         if($duplicates)$this->repeatName = Arr::first($duplicates);

        // 统计值的出现次数
        return count($values) === count(array_unique($values));
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return "名称{$this->repeatName}重复,请检查";
    }
}
